#include "widget.h"
#include "ui_widget.h"

#include "application.h"
#include <QtWebKit>

#include "t_youtube_dump_lib.h"

#include <windows.h>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject()));
#if 0x0
    QNetworkDiskCache *v_disk_cache = new QNetworkDiskCache(this);
    QString v_cache_location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
    qDebug() << "[v_cache_location]" << v_cache_location;
    v_disk_cache->setCacheDirectory(v_cache_location);
    ui->webView->page()->networkAccessManager()->setCache(v_disk_cache);
#endif
    this->setWindowTitle("Download YouTube");
    ui->pushButton->setText("終了");
    //this->resize(800, 600);
    this->resize(800, 300);

#if 0x0
    ui->webView->setUrl(QUrl("qrc:/page/page1.html"));
#else
    QFile v_page1(":/page/page1.html");
    if(v_page1.open(QIODevice::ReadOnly))
    {
        QByteArray v_page1_cont = v_page1.readAll();
        ui->webView->setHtml(QString::fromUtf8(v_page1_cont));
    }
#endif
}

Widget::~Widget()
{
    delete ui;
}

void Widget::handleMessage(const QString& message)
{
    this->showNormal();
    ::SetWindowPos(effectiveWinId(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
    ::SetWindowPos(effectiveWinId(), HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
    //this->activateWindow();
}

void Widget::populateJavaScriptWindowObject()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("web1", this);
    //ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("list1", &this->m_video_list);
    //ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("page1", g_Env->page1);

}

void Widget::dbgmsg(QString v_msg)
{
    qDebug(v_msg.toLocal8Bit().constBegin());
}

void Widget::submitUrlToDownload(QString a_url)
{
    qDebug() << "[a_url]" << a_url;
    ////QMessageBox::information(0, "[Widget::submitUrlToDownload(): a_url]", a_url);
    QUrl v_url(a_url);
    QString v_id = v_url.queryItemValue("v");
    ////QMessageBox::information(0, "[Widget::submitUrlToDownload(): v_id]", v_id);
    Application *v_app = (Application *)qApp;
    QFile v_program(v_app->f_download_exe);
    QStringList v_arguments;
    v_arguments << v_id;
    QProcess::startDetached(v_program.fileName(), v_arguments);
}

void Widget::on_pushButton_clicked()
{
    qApp->quit();
}
